package com.thesis.student.controller;

import com.alibaba.fastjson.JSONObject;
import com.thesis.manage.common.constant.OpenException;
import com.thesis.manage.common.exception.CommonException;
import com.thesis.manage.common.utils.Result;
import com.thesis.manage.domain.Student;
import com.thesis.manage.service.model.RoleEnum;
import com.thesis.manage.service.model.StateCodeEnum;
import com.thesis.manage.service.module.dto.LoginDTO;
import com.thesis.manage.service.module.dto.UserLoginDTO;
import com.thesis.manage.service.module.vo.LoginVO;
import com.thesis.student.feign.LoginRegisterService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author php
 * @date 2018/3/12
 */
@RequestMapping("/loginRegister")
@RestController
public class LoginRegisterController extends BaseController {

    @Resource
    private LoginRegisterService loginRegisterService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginDTO loginDTO) {
        return buildMessage(() -> {
            Result result = loginRegisterService.login(loginDTO.getUsername(), loginDTO.getPassword(), RoleEnum.STUDENT.getValue());
            LoginVO loginVO = new LoginVO();
            if (result != null && result.getStatus() == StateCodeEnum.SUCCESS.getValue().intValue()) {
                Object data = result.getData();
                UserLoginDTO userLoginDTO = JSONObject.parseObject(data.toString(), UserLoginDTO.class);
                Student student = JSONObject.parseObject(userLoginDTO.getUserInfo(), Student.class);
                loginVO.setUsername(student.getName());
                loginVO.setImage(student.getImage());
                loginVO.setToken(userLoginDTO.getToken());
            } else {
                throw new CommonException("login.failed", "用户名或密码错误");
            }
            return loginVO;
        });
    }

    @DeleteMapping("/logout")
    public Map<String, Object> logout() {
        return buildMessage(() -> {
            loginRegisterService.logout(getToken());
            return null;
        });
    }

    /**
     * 查看个人信息
     */
    @GetMapping("/info")
    public Map<String, Object> info() {
        return buildMessage(() -> {
            Result result = getUser();
            return JSONObject.parseObject(result.getData().toString(), Student.class);
        });
    }

}
